<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue Compoents</title>
</head>
<body>
	<div id="app">
		<currency-input label="Price" v-model="price"></currency-input>
		<currency-input label="Shipping" v-model="shipping"></currency-input>
		<currency-input label="Handling" v-model="handling"></currency-input>
		<currency-input label="Discount" v-model="discount"></currency-input>
		<p>Total: ${{ total }}</p>
	</div>

	<hr>

	<div id="test1">
		<comp1></comp1>
		<comp2></comp2>
	</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/chrisvfritz/5f0a639590d6e648933416f90ba7ae4e/raw/98739fb8ac6779cb2da11aaa9ab6032e52f3be00/currency-validator.js"></script>

<script>
	var currencyInput = Vue.extend({
		template:'<div>\
					<label v-if="label">{{label}}</label>\
				  	$\
				  	<input type="text" ref="input" :value="value"\
				  		@input ="updateValue($event.target.value)"\
						@focus="selectAll"\
						@blur="formateValue"\
				  	/>\
				  </div>',
		props: {
			value:{
				type:Number,
				default:0
			},
			label:{
				type:String,
				default:''
			}
		},
		mounted() {
			this.formateValue();
		},
		methods:{
			updateValue(value) {
				var result = currencyValidator.parse(value,this.value);
				if(result.warning) {
					this.$refs.input.value = result.value
				}

				this.$emit('input',result.value);
			},
			formateValue() {
				this.$refs.input.value = currencyValidator.format(this.value)
			},
			selectAll(event) {
				setTimeout(function(){
					event.target.select();
				},0);
			}
		}
	});

	var app = new Vue({
		el:"#app",
		data: {
			price:0,
			shipping:0,
			handling:0,
			discount:0
		},

		computed:{
			total() {
				var mytotal = ((this.price*100 + this.shipping * 100 + this.handling * 100 - this.discount * 100)/100).toFixed(2);
				return mytotal;
			}
		},

		components:{
			'currency-input':currencyInput,
		}
	});

//*********************************************非父子组件之前的数据传递

	let Hub = new Vue();

	var comp1 = Vue.extend({
		template:'<input type="text" v-model="myinfo"/>',
		data() {
			return{
				myinfo: 0,
			}
		},

		created(){
			Hub.$on('add',(info)=>{
				this.myinfo ++;
			})
		}
		// methods: {
		// 	add() {
		// 		this.myinfo ++;
		// 	}
		// }
	});
	var comp2 = Vue.extend({
		template:'<input type="button" @click="add" :value="msg"/>',
		data() {
			return{
				msg:'点击触发非父子组件之间的数据传递'
			};
		},
		methods: {
			add() {
				 Hub.$emit('add',1);
			}
		}
	});

	var test1 = new Vue({
		el:"#test1",
		data:{
			privateState: {},
    		sharedState: store.state
		}
		components:{
			comp1:comp1,
			comp2:comp2
		}
	});
</script>
</html>